//
//  JZIDFARequest.swift
//  Example
//
//  Created by S JZ on 2024/1/30.
//

import UIKit
import Foundation

#if canImport(AppTrackingTransparency)
import AppTrackingTransparency
#endif

#if canImport(AdSupport)
import AdSupport
#endif

public class JZIDFARequest {
    @objc public static func requestIdfa() -> String {
        var deviceIdentifier: String = ""
        
        let idfa = authorization().replacingOccurrences(of: "-", with: "").replacingOccurrences(of: "0", with: "")
        if idfa.isEmpty {
            deviceIdentifier = UIDevice.current.identifierForVendor?.uuidString ?? ""
        }else {
            deviceIdentifier = idfa
        }
        
        return deviceIdentifier
    }
    
    static func authorization() -> String {
        var idfaStr: String = ""
        if #available(iOS 14.0, *) {
#if canImport(AppTrackingTransparency)
            ATTrackingManager.requestTrackingAuthorization { status in
                if status == .authorized {
                    idfaStr = self.getIdfaStr()
                }
            }
#endif
        }else {
            idfaStr = self.getIdfaStr()
        }
        
        return idfaStr
    }
    
    static func getIdfaStr() -> String {
#if canImport(AdSupport)
        return ASIdentifierManager.shared().advertisingIdentifier.uuidString
#endif
        return ""
    }
}

